<template>
  <div class="app-container">
    <div class="business">
      <el-row :gutter="24">
        <el-col :span="8" >
          <el-row :gutter="24">
            <el-col :span="8" >
                <el-button type="default" @click="addClick">添加</el-button>
            </el-col>
            <el-col :span="16" >
              <el-input placeholder="搜索关键字" v-model="filterText" class="input-with-select">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-col>
          </el-row>
          <div class="filter-tree">
            <el-tree
              :data="businessTreeList"
              :props="defaultProps"
              :default-expand-all="expandAll"
              :highlight-current="true"
              :filter-node-method="filterNode"
              ref="tree"
              @node-click="treeNodeClick">
            </el-tree>
          </div>
        </el-col>
        <el-col :span="16">
          <el-form ref="businessForm" size="small" :model="businessForm" label-width="100px" v-show="showForm" :rules="businessFormRules">
            <el-form-item label="业务线名称" prop="name">
              <el-input v-model="businessForm.name" :disabled="disabled" placeholder="请输入业务线名称"></el-input>
            </el-form-item>
            <el-form-item label="业务线简称" prop="letter">
              <el-input v-model="businessForm.letter" :disabled="disabled" placeholder="请输入业务线简称"></el-input>
            </el-form-item>
            <el-form-item label="上层业务线" prop="pid">
              <el-select class="select" v-model="businessForm.pid" :disabled="disabled" size="small" placeholder="请选择上级业务线">
                <el-option v-for="(item, index) in businessChoiceList"
                           :key="index" :value="item.id" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运维接口人" prop="op_interface">
              <el-select multiple class="select" v-model="businessForm.op_interface" :disabled="disabled" placeholder="请输选择运维接口人">
                <el-option v-for="(item, index) in userList"
                           :key="index" :value="item.id" :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开发接口人" prop="dev_interface">
              <el-select multiple class="select" v-model="businessForm.dev_interface" :disabled="disabled"  placeholder="请选择开发接口人">
                <el-option v-for="(item, index) in userList"
                           :key="index" :value="item.id" :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitEdit" :disabled="disabled">提交</el-button>
              <el-button type="primary" @click="handleEdit" :disabled="buttonDisabled">修改</el-button>
              <el-button type="primary" @click="handleDelete" :disabled="buttonDisabled">删除</el-button>
            </el-form-item>
          </el-form>

          <el-table class="table" v-loading="isLoading" element-loading-text="拼命加载中" :data="serverList"
            border v-show="showServerListTable">
            <el-table-column sortable prop="idc.name" label="机房" align="center"></el-table-column>
            <el-table-column sortable prop="hostname" label="主机名" align="center"></el-table-column>
            <el-table-column sortable prop="ip" label="管理IP" align="center"></el-table-column>
            <el-table-column sortable prop="status" label="状态" align="center"></el-table-column>
            <el-table-column sortable prop="last_check" label="LAST CHECK" align="center"></el-table-column>
          </el-table>
          <div class="text-center" v-show="serverListTotal>5">
            <el-pagination
              background
              @current-change="handleCurrentChange"
              layout="total, prev, pager, next, jumper"
              :current-page.sync="server_params.page"
              :total="serverListTotal">
            </el-pagination>
          </div>

        </el-col>
      </el-row>

    </div>
  </div>
</template>

<script>
  import { getUserList } from '@/api/users'
  import { getBusinessTree, getBusinessInfo, deleteBusiness, createBusiness, updateBusiness, getServersList } from '@/api/resources'
  // , getBusinessList

  export default {
    name: 'business',
    data() {
      return {
        // 业务线树
        filterText: '',
        businessTreeList: [],
        expandAll: false,
        state: 0,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // 表单
        businessList: [],
        businessChoiceList: [],
        userList: [],
        businessForm: {
          name: '',
          letter: '',
          dev_interface: '',
          op_interface: '',
          pid: ''
        },
        businessFormRules: {
          name: [
            { required: true, trigger: 'blur', message: '请输入业务线名称' }
          ],
          pid: [
            { required: true, trigger: 'blur', message: '请选择上级业务线' }
          ],
          letter: [
            { required: true, trigger: 'blur', message: '请输入业务线简称' }
          ],
          interface_user: [
            { required: true, trigger: 'blur', message: '请选择接口人' }
          ]
        },
        actionFlag: '', // 使用表单时判别是新增或者编辑
        // 二级业务线的服务器列表
        serverList: [],
        serverListTotal: 0,
        server_params: {
          page: 1,
          business_line: '',
          page_size: 10
        },
        // 状态变量
        showServerListTable: false,
        isLoading: false,
        buttonDisabled: false,
        disabled: false,
        showForm: false
      }
    },
    created() {
      this.state = 1
    },
    watch: {
      state() {
        this.getBusinessTreeInfo()
        getUserList({ page_size: 0 }).then(
          res => {
            this.userList = res
          })
      },
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      fetchServerList() {
        this.isLoading = true
        getServersList(this.server_params).then(
          res => {
            this.serverList = res.results
            // console.log('aaaa=>', this.serverList)
            this.isLoading = false
          }
        ).catch(
          () => {
            this.$message.error('获取业务线下的服务器失败')
          }
        )
      },
      // 点击tree节点时右侧表单展示被点击业务线的所有信息
      treeNodeClick(data) {
        this.$refs['businessForm'].resetFields()
        getBusinessInfo(data.id).then(
          res => {
            const op_interface = []
            const dev_interface = []
            res.op_interface.forEach(
              item => {
                op_interface.push(item.id)
              })
            res.dev_interface.forEach(
              item => {
                dev_interface.push(item.id)
              })
            const { id, pid, letter, name } = res
            this.businessForm = { id, pid, letter, name, op_interface, dev_interface }
            this.disabled = true
            this.buttonDisabled = false
            this.showForm = true
            if (pid === 0) {
              this.showServerListTable = false
            } else {
              this.server_params.page = 1
              this.server_params.business_line = data.id
              this.serverList = []
              this.fetchServerList()
              this.showServerListTable = true
            }
          })
      },
      getBusinessTreeInfo() {
        getBusinessTree().then(
          res => {
            this.businessTreeList = res
            this.businessChoiceList = [{ id: 0, label: '顶级' }].concat(res)
          })
      },
      addClick() {
        this.actionFlag = 'add'
        this.$refs['businessForm'].resetFields()
        this.showForm = true
        this.showServerListTable = false
        this.disabled = false
        this.buttonDisabled = true
      },
      submitEdit() {
        this.$refs['businessForm'].validate((valid) => {
          if (!valid) {
            return
          }
          if (this.actionFlag === 'add') {
            const params = Object.assign({}, this.businessForm)
            createBusiness(params).then(
              () => {
                this.$refs['businessForm'].resetFields()
                this.$message.success('添加业务线成功')
                this.showForm = false
                this.showServerListTable = false
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.getBusinessTreeInfo()
              }).catch(
              () => {
                this.$message.error('添加业务线失败')
              })
          } else {
            const id = this.businessForm.id
            delete this.businessForm.id
            const params = Object.assign({}, this.businessForm)
            updateBusiness(id, params).then(
              () => {
                this.$message.success('修改业务线成功')
                this.showForm = false
                this.showServerListTable = false
                this.disabled = true
                // this.$message.success('操作成功')
                this.getBusinessTreeInfo()
              }).catch(
              () => {
                this.$message.error('修改业务线失败')
              }
            )
          }
        })
      },
      handleEdit() {
        this.actionFlag = 'edit'
        this.disabled = false
        this.buttonDisabled = true
      },
      handleDelete() {
        this.$confirm('此操作将删除该业务线, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          () => {
            deleteBusiness(this.businessForm.id).then(
              () => {
                this.$message.success('删除业务线成功')
                this.showForm = false
                this.showServerListTable = false
                this.getBusinessTreeInfo()
              }).catch(
              error => {
                if (error.response.status === 400) {
                  this.$message.error('删除业务线失败，请先删除子项或移出服务器')
                } else {
                  this.$message.error('删除业务线失败，其他错误')
                }
              })
          })
      },
      handleCurrentChange(val) {
        this.server_params.page = val
        this.fetchData()
      }
    }
  }
</script>

<style lang="scss" scoped>
    .business {
      .filter-tree {
        margin-top: 20px;
      }
      .select {
        width: 100%;
      }
    }
</style>
